package com.faith.timefloating;

import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.view.MotionEventCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.faith.timefloating.db.DataBaseHelper;
import com.faith.timefloating.model.Event.FailResponse;
import com.faith.timefloating.model.Event.GetFeedSuccess;
import com.faith.timefloating.myutils.Constants;
import com.faith.timefloating.network.NetOperator;
import com.faith.timefloating.utils.Common;
import com.faith.timefloating.utils.DummyAlg;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

import de.greenrobot.event.EventBus;

public class TimeFloatingService extends Service {

	private static final int ONGOING_NOTIFICATION_ID = 23;

	public static  int ID_NOTIFICATION = 2018;

	private WindowManager windowManager;
	private ImageView ico_close;
	private ImageView ico_lock;
	private ImageView dummy;
	private TextView ico_battery;
	private Handler timer;
	private TextView timelbl;
	long lastPressTime;
	int fontsize=9;
	int fontcolorindex=0;
	private int interval=1000;
	private boolean waitAnotherClick=false;
	String mode=Constants.MODE.LONG_MODE.toString();
	private static boolean isHide=false;
	private boolean refresh=false;
	private boolean isStartedForceground=false;
	protected Date date;
	protected long lastPressUpTime;
	protected int lastY;
	protected int lastX;
	private RemoteViews contentRemoteViews;
	private NotificationManager notiManager;
	private Notification notification;
	private LayoutParams params;
	private LayoutParams paramsMenuClose;
	private LayoutParams paramsMenuLock;
	private LayoutParams paramsMenuBattery;
	private SharedPreferences shared;
	private int centerX,centerY;
	private static boolean isLocked=false;
	private static boolean isHideOutIcon=true;
	private Handler handler;
	private TextView batteryIndicator;
	private Tracker mTracker;
	private LayoutParams biParams;
	private boolean isCheckingMsgs = false;
	private volatile boolean enableShowBattery;
	private DataBaseHelper dbHelper;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		//get action visible the TIME
		if(intent!=null&&intent.getAction()!=null){
			if(intent.getAction().equalsIgnoreCase(Constants.VISIBLE_THETIME_ACTION)){
				doVisibleTheTime();
				return START_STICKY;
			}else if(intent.getAction().equalsIgnoreCase(Constants.UPDATE_MSGs)){
				if(!isCheckingMsgs){
					isCheckingMsgs = true;
					NetOperator net=NetOperator.getInstance().init(this);
					net.getFBLinkFeedList();
					MyApplication.chatContents = dbHelper.getMsgs();
				}
			}
		}
		
		if(intent!=null&&intent.getExtras()!=null){
			refresh=intent.getExtras().getBoolean(Constants.ACTION_REFRESH);
			if(intent.getExtras().containsKey(Constants.SHOW_BATTERY)){
				enableShowBattery = intent.getExtras().getBoolean(Constants.SHOW_BATTERY);
			}
			if(refresh){
				if(timelbl!=null){
					if(timelbl.getParent()!=null){
					}else{
						params.x = lastX;
						params.y = lastY;
						windowManager.addView(timelbl, params);
					}
					timelbl.setTextSize(intent.getExtras().getInt(Constants.FONT_SIZE_KEY));
					timelbl.setBackgroundColor(intent.getExtras().getInt(Constants.FONT_COLOR_BG_KEY));
					int color=intent.getExtras().getInt(Constants.FONT_COLOR_KEY);
					timelbl.setTextColor(color);
					
					batteryIndicator.setTextColor(color);
					batteryIndicator.setTextSize(intent.getExtras().getInt(Constants.FONT_SIZE_KEY));
					batteryIndicator.setBackgroundColor(intent.getExtras().getInt(Constants.FONT_COLOR_BG_KEY));
					ico_battery.setTextColor(Color.parseColor("#1eac21"));
					String newTimeMode=intent.getExtras().getString(Constants.TIME_MODE);
					if(newTimeMode!=mode){
						//restart timer
						if(newTimeMode.equalsIgnoreCase(Constants.MODE.LONG_MODE.toString())){
								interval=1000;
						}else{
							interval=60000;
						}
						timer=new Handler();
						refresh=false;
						timer.postDelayed(updater, 23);
					}
					
				}
			}else{
				
				paramsMenuClose.x=centerX-10;
				paramsMenuClose.y=centerY;
				paramsMenuLock.y=centerY;
				paramsMenuLock.x=centerX+10;
				paramsMenuBattery.x=paramsMenuClose.x;
//				float converted=CommonUtils.convertPixelsToDp(dummy.getMeasuredHeight(), getApplicationContext());
				paramsMenuBattery.y=centerY-(int)(dummy.getMeasuredHeight()*0.5f);
				paramsMenuBattery.width=dummy.getMeasuredHeight();
			}
		}else{
//			visibleTheTime();
		}
		return START_STICKY;
	}
	private void doVisibleTheTime() {
		try{
			mTracker.sendEvent("Button Click "+Common.getVersionCode(this), "Click VISIBLE the TIME!", "Click VISIBLE the TIME from noti!", Long.valueOf(1));
			
			}catch(IllegalStateException ex){
			if(ex.getMessage().contains("Tracker closed")){
				initGATracker();
				mTracker.sendEvent("Button Click "+Common.getVersionCode(this), "Click VISIBLE the TIME!", "Click VISIBLE the TIME from noti!", Long.valueOf(1));
			}
		}
		
		if(timelbl!=null&&!shared.getBoolean(Constants.VISIBLE_THETIME_STATE, false)){
			params.x = lastX;
			params.y = lastY;
			windowManager.addView(timelbl, params);
			isHide=false;
			contentRemoteViews.setViewVisibility(R.id.visible, View.GONE);
			shared.edit().putBoolean(Constants.VISIBLE_THETIME_STATE, true).commit();
			notiManager.notify(ONGOING_NOTIFICATION_ID, notification);
			try{
				mTracker.sendView("Here I Am! "+Common.getVersionCode(this));
				shared.edit().putBoolean(Common.SHARED_VISIBILITY, true).commit();
			}catch(IllegalStateException ex){
				if(ex.getMessage().contains("Tracker closed")){
					initGATracker();
					mTracker.sendView("Here I Am! "+Common.getVersionCode(this));
					shared.edit().putBoolean(Common.SHARED_VISIBILITY, true).commit();
				}
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}
	private void visibleTheTime() {
		if(isHide){
			params.x = lastX;
			params.y = lastY;
			windowManager.addView(timelbl, params);
			contentRemoteViews.setViewVisibility(R.id.visible, View.VISIBLE);
			notiManager.notify(ONGOING_NOTIFICATION_ID, notification);
			isHide=false;
		}
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
			isLanscape = true;
		}else{
			isLanscape = false;
		}
		if(isHideOutIcon){
			return;
		}
		updateParams();
	}
	
	private boolean isLanscape = false;

	private VisibleTheTimeListener visibleTheTimeListener;
	private void updateParams() {
		Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
	    int orientation = display.getOrientation();
	    switch(orientation) {
        case 0://portrait
        	paramsMenuClose.x=centerX-10;
			paramsMenuClose.y=centerY;
			paramsMenuLock.y=centerY;
			paramsMenuLock.x=centerX+10;
			paramsMenuBattery.x=paramsMenuClose.x;
			paramsMenuBattery.y=centerY-(int)(dummy.getMeasuredHeight()*0.5f);
			windowManager.updateViewLayout(ico_lock, paramsMenuLock);
			windowManager.updateViewLayout(ico_close, paramsMenuClose);
			windowManager.updateViewLayout(ico_battery, paramsMenuBattery);
            break;
        case 1:
        	paramsMenuClose.x=centerY-10;
			paramsMenuClose.y=centerX;
			paramsMenuLock.y=centerX;
			paramsMenuLock.x=centerY+10;
			paramsMenuBattery.x=paramsMenuClose.x;
			paramsMenuBattery.y=centerX-(int)(dummy.getMeasuredHeight()*0.5f);
			windowManager.updateViewLayout(ico_lock, paramsMenuLock);
			windowManager.updateViewLayout(ico_close, paramsMenuClose);
			windowManager.updateViewLayout(ico_battery, paramsMenuBattery);
            break;
    }
	}
	@SuppressLint("NewApi")
	@Override 
	public void onCreate() {
		super.onCreate();
		EventBus.getDefault().register(this);
		notiManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
		timelbl = new TextView(this);
		ico_close=new ImageView(this);
		ico_lock=new ImageView(this);
		dbHelper = new DataBaseHelper(this);
		visibleTheTimeListener = new VisibleTheTimeListener();
		registerReceiver(visibleTheTimeListener, new IntentFilter(Constants.VISIBLE_THETIME_ACTION));
		initGATracker();
		centerX=MyApplication.getSharedPreferences().getInt(Constants.CENTER_X_POS, 100);
		centerY=MyApplication.getSharedPreferences().getInt(Constants.CENTER_Y_POS, 100);
		handler=new Handler();
		ico_lock.setImageResource(isLocked?R.drawable.lock:R.drawable.unlock);
		ico_close.setImageResource(R.drawable.invisible);
		dummy=new ImageView(this);
		dummy.setImageResource(R.drawable.invisible);
		dummy.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
		ico_battery=new Button(this);
		ico_battery.setBackgroundColor(Color.TRANSPARENT);
		ico_battery.setTextSize(12);
		timelbl.setText("23 : 23 : 23");
		shared=getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		timelbl.setTextSize(shared.getInt(Constants.FONT_SIZE_KEY,19));
		int bgColor=shared.getInt(Constants.FONT_COLOR_BG_KEY,Color.WHITE);
		timelbl.setBackgroundColor(bgColor);
		if(bgColor==0){
			shared.edit().putInt(Constants.FONT_COLOR_BG_KEY, bgColor).commit();
		}
		timelbl.setPadding(5, 0, 5, 0);
		int color=shared.getInt(Constants.FONT_COLOR_KEY,Color.parseColor("#1eac21"));
		timelbl.setTextColor(color);
		ico_battery.setTextColor(Color.parseColor("#1eac21"));
		String newTimeMode=shared.getString(Constants.TIME_MODE,mode);
		if(newTimeMode!=mode){
			if(newTimeMode.equalsIgnoreCase(Constants.MODE.LONG_MODE.toString())){
					interval=1000;
			}else{
				interval=60000;
			}
		}
		
		enableShowBattery=shared.getBoolean(Constants.SHOW_BATTERY, true);
//		timelbl.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
//		w=timelbl.getMeasuredWidth();
//		h=timelbl.getMeasuredHeight();
		timer =new Handler();
		timer.postDelayed(updater, 23);
		batteryIndicator = new TextView(this);
		batteryIndicator.setTextColor(color);
		batteryIndicator.setTextSize(shared.getInt(Constants.FONT_SIZE_KEY,15));
		batteryIndicator.setBackgroundColor(bgColor);
		biParams =new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		biParams.gravity = Gravity.TOP|Gravity.LEFT;
		biParams.x = 0;
		biParams.y = 0;
		biParams.windowAnimations=android.R.style.Animation_Translucent;
		
		params = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		paramsMenuClose = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		paramsMenuClose.gravity=Gravity.BOTTOM|Gravity.LEFT;
		paramsMenuClose.windowAnimations = R.style.myOpenMenuStyle;
		//
		paramsMenuLock = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		paramsMenuLock.gravity=Gravity.BOTTOM|Gravity.RIGHT;
		paramsMenuLock.windowAnimations=android.R.style.Animation_Translucent;
		//
		paramsMenuBattery = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		paramsMenuBattery.gravity=Gravity.TOP|Gravity.LEFT;
		paramsMenuBattery.windowAnimations=android.R.style.Animation_Translucent;
		//
		params.gravity = Gravity.LEFT;
		int lastx=shared.getInt(Constants.LAST_X_POS, 0);
		int lasty=shared.getInt(Constants.LAST_Y_POS, 100);
		params.x = lastx;
		params.y = lasty;
		if(shared.getBoolean(Constants.VISIBLE_THETIME_STATE, true)){
			windowManager.addView(timelbl, params);
		}
//		try {
			timelbl.setOnTouchListener(new View.OnTouchListener() {
				private WindowManager.LayoutParams paramsF = params;
				private int initialX;
				private int initialY;
				private float initialTouchX;
				private float initialTouchY;
				@Override public boolean onTouch(View v, MotionEvent event) {
					final int action = MotionEventCompat.getActionMasked(event);
					switch (action) {
					case MotionEvent.ACTION_DOWN:
						lastPressTime = System.currentTimeMillis(); 
						initialX = paramsF.x;
						initialY = paramsF.y;
						initialTouchX = event.getRawX();
						initialTouchY = event.getRawY();
						timer.postDelayed(new Runnable() {
							
							@Override
							public void run() {
								waitAnotherClick=false;
							}
						}, 1000);
						Log.e("FloatingService","Action down");
						if(isHideOutIcon){
							showMenu();
						}else{
							try{
								windowManager.removeView(ico_lock);
								windowManager.removeView(ico_close);
								windowManager.removeView(ico_battery);
							}catch(IllegalArgumentException ex){}
							isHideOutIcon = true;
						}
						break;
					case MotionEvent.ACTION_UP:
//						lastPressUpTime = System.currentTimeMillis(); 
//						if(lastPressUpTime-lastPressTime<500&&waitAnotherClick){
//							if(isHideOutIcon){
//								showMenu();
//							}else{
//								windowManager.removeView(ico_lock);
//								windowManager.removeView(ico_close);
//								try{
//									windowManager.removeView(ico_battery);
//								}catch(IllegalArgumentException ex){}
//								isHideOutIcon=true;
//							}
//							break;
//						}else if(lastPressUpTime-lastPressTime<500){
//							waitAnotherClick=true;
//						}
						shared.edit().putInt(Constants.LAST_X_POS, lastX).commit();
						shared.edit().putInt(Constants.LAST_Y_POS, lastY).commit();
						break;
					case MotionEvent.ACTION_MOVE:
						if(!isHideOutIcon){
							if((initialX + (int)(event.getRawX() - initialTouchX) - paramsF.x < 5) && (initialY +  (int)(event.getRawY() - initialTouchY) - lastY < 5)){
								return false;
							}
						}
						Log.e("FloatingService","Action MOVE");
						if(isLocked){
							break;
						}
						if(!isHideOutIcon){
							try{
								windowManager.removeView(ico_lock);
								windowManager.removeView(ico_close);
								windowManager.removeView(ico_battery);
							}catch(IllegalArgumentException ex){}
							isHideOutIcon = true;
						}
						
						paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
						paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
						lastX=paramsF.x;
						lastY=paramsF.y;
						windowManager.updateViewLayout(timelbl, paramsF);
						break;
					}
					return false;
				}
			});
			ico_close.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					try{
						mTracker.sendEvent("Button Click "+Common.getVersionCode(TimeFloatingService.this), "Click invisible the TIME", "Click invisible the TIME", Long.valueOf(1));
					}catch(Exception ex){
						ex.printStackTrace();
					}
					if(!isHide){
						invisibleTheTime();
					}
					
				}
			});
			ico_lock.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					mTracker.sendEvent("Button Click "+Common.getVersionCode(TimeFloatingService.this), "Click lock position the TIME", "Click lock position the TIME", Long.valueOf(1));
					isLocked=!isLocked;
					ico_lock.setImageResource(isLocked?R.drawable.lock:R.drawable.unlock);
				}
			});
			if(!isStartedForceground){
				Intent notifyIntent = null;
				if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
					notifyIntent = new Intent();
				}else{
					notifyIntent = new Intent("notification");
				}
				notifyIntent.setClass(this, FirstActivity.class);
			    PendingIntent pending = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				contentRemoteViews = new RemoteViews(getPackageName(), R.layout.notibar);
				Intent visibleIntent=new Intent(Constants.VISIBLE_THETIME_ACTION);
				PendingIntent visibleNotiIntent=PendingIntent.getBroadcast(this, 0, visibleIntent, 0);
				contentRemoteViews.setViewVisibility(R.id.visible, shared.getBoolean(Constants.VISIBLE_THETIME_STATE, true)?View.GONE:View.VISIBLE);
				notification = new Notification(R.drawable.ic_launcher, "Here I Am!", System.currentTimeMillis());
				notification.contentIntent=pending;
//				if(Build.VERSION.SDK_INT>=11){
//					contentRemoteViews.setPendingIntentTemplate(R.id.visible, visibleNotiIntent);
//				}else{
					contentRemoteViews.setOnClickPendingIntent(R.id.visible, visibleNotiIntent);
//				}
				
				notification.contentView=contentRemoteViews;
				startForeground(ONGOING_NOTIFICATION_ID,notification);
				isStartedForceground=true;
				try{
					mTracker.sendView("Here I Am! "+Common.getVersionCode(this));
					shared.edit().putBoolean(Common.SHARED_VISIBILITY, true).commit();
				}catch(IllegalStateException ex){
					if(ex.getMessage().contains("Tracker closed")){
						initGATracker();
						mTracker.sendView("Here I Am! "+Common.getVersionCode(this));
						shared.edit().putBoolean(Common.SHARED_VISIBILITY, true).commit();
					}
				}
				catch(Exception ex){
					ex.printStackTrace();
				}
			}
			handler.postDelayed(showBattery,5000);
	}
	
	Runnable showBattery = new Runnable() {
		@Override
		public void run() {
			if(enableShowBattery){
				batteryIndicator.setText(getBatteryLevel()+" %");
				windowManager.addView(batteryIndicator, biParams);
				handler.postDelayed(closeBattery, 8000);
			}else{ 
				handler.postDelayed(showBattery, 3*60*1000);
			}
		}
	};
	
	Runnable closeBattery = new Runnable() {
		@Override
		public void run() {
			windowManager.removeView(batteryIndicator);
			handler.postDelayed(showBattery, 3*60*1000);
		}
	};
	
	private void initGATracker() {
		GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(this);
		mTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
	}
	
	Runnable updater=new Runnable() {
		
		@Override
		public void run() {
			if(refresh){
				return;
			}
			date=new Date();
			if(interval==1000){
				timelbl.setText((date.getHours()>12?date.getHours()-12:date.getHours())+" : "+(date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes())+" : "+(date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds()));
			}else{
				timelbl.setText((date.getHours()>12?date.getHours()-12:date.getHours())+" : "+(date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes()));
			}
			timer.postDelayed(this, interval);
		}
	};

	@Override
	public void onDestroy() {
		handler.removeCallbacks(showBattery);
		unregisterReceiver(visibleTheTimeListener);
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	
	private void showMenu(){
		try {
			mTracker.sendEvent("Button Click "+Common.getVersionCode(this), "Click the TIME to show options", "Click the TIME to show options", Long.valueOf(1));
		} catch (Exception e) {
			e.printStackTrace();
		}
		isHideOutIcon=false;
//		if(paramsMenuClose.x==0||paramsMenuClose.x<=ico_close.getWidth()){
			if(centerX!=100){
				paramsMenuLock.x=(isLanscape?centerY+ico_close.getWidth()/2:centerX-ico_close.getWidth()/2);
				paramsMenuLock.y=(isLanscape?centerX+ico_close.getHeight()/2:centerY+ico_close.getHeight()/2);
				
				paramsMenuClose.x=(isLanscape?centerY+ico_close.getWidth()/2:centerX+ico_close.getWidth()/2);
				paramsMenuClose.y=(isLanscape?centerX+ico_close.getHeight()/2:centerY+ico_close.getHeight()/2);
				
				paramsMenuBattery.x=(isLanscape?centerY+ico_close.getWidth()/2:centerX);
				paramsMenuBattery.y=(isLanscape?centerX+ico_close.getHeight()/2:centerY);
			}
//		}
		ico_battery.setText(getBatteryLevel()+"");
		try{
			windowManager.addView(ico_close, paramsMenuClose);
			windowManager.addView(ico_lock, paramsMenuLock);
			windowManager.addView(ico_battery, paramsMenuBattery);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	private void invisibleTheTime() {
		mTracker.close();
		windowManager.removeView(timelbl);
		windowManager.removeView(ico_close);
		windowManager.removeView(ico_battery);
		windowManager.removeView(ico_lock);
		isHideOutIcon=true;
		isHide=true;
		contentRemoteViews.setViewVisibility(R.id.visible, View.VISIBLE);
		notiManager.notify(ONGOING_NOTIFICATION_ID, notification);
		shared.edit().putBoolean(Common.SHARED_VISIBILITY, false).commit();
		shared.edit().putBoolean(Constants.VISIBLE_THETIME_STATE, false).commit();
	}
	public static boolean isHide(){
		return isHide;
	}
	
	public int getBatteryLevel() {
	    Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
	    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
	    if(level == -1 || scale == -1) {
	        return 50;
	    }
	    return (int)(((float)level / (float)scale) * 100.0f); 
	}
	
	public void onEventMainThread(GetFeedSuccess event){
		DummyAlg da= new DummyAlg(Constants.DIGEST_STRING, Constants.DUMMY_STRING);
		String msg="";
		String[] splitData= new String[2];
		try
		{
		if(event.feeds != null && event.feeds.size()>0){
			int size = event.feeds.size();
			for(int i=0;i<size;i++){
				msg = event.feeds.get(i).getContent();
				msg = new String(da.decrypt(msg));
				splitData = msg.split("@");
				event.feeds.get(i).date = splitData[0];
			}
			dbHelper.insertMsgs(event.feeds);
		}
		}catch (Exception ex) {
			ex.printStackTrace();
		}
		MyApplication.chatContents = dbHelper.getMsgs();
		isCheckingMsgs = false;
	}
	
	public void onEventMainThread(FailResponse event){
			Log.e("TimeFloating", "Cannot get msg");
			isCheckingMsgs = false;
	}
	
	public class VisibleTheTimeListener extends BroadcastReceiver {
		@Override
		    public void onReceive(Context context, Intent intent) {
		        doVisibleTheTime();
		    }

		}
	
}